package billcategory

import (
	"errors"
	"gitee.com/xiaozefeng/billing-server/handler"
	"gitee.com/xiaozefeng/billing-server/handler/resp"
	"gitee.com/xiaozefeng/billing-server/model"
	"gitee.com/xiaozefeng/billing-server/pkg/errno"
	"github.com/gin-gonic/gin"
	"github.com/lexkong/log"
	"strconv"
)

func bind(c *gin.Context) (*model.BillCategory, error) {
	var b model.BillCategory
	if err := c.Bind(&b); err != nil {
		return &b, err
	}
	return &b, nil
}

func Create(c *gin.Context) {
	b, err := bind(c)
	if err != nil {
		handler.SendResponse(c, errno.ErrBind, nil)
		return
	}
	log.Infof("create bill: %#v", *b)

	// todo validation

	if err := b.Create(); err != nil {
		handler.SendResponse(c, errno.ErrDatabase, nil)
		log.Errorf(err, "create bill data error")
		return
	}

	handler.SendResponse(c, nil, b)
}

func Update(c *gin.Context) {
	b, err := bind(c)
	if err != nil {
		handler.SendResponse(c, errno.ErrBind, nil)
		return
	}
	log.Infof("update bill: %#v", *b)

	if err := b.Update(); err != nil {
		handler.SendResponse(c, errno.ErrDatabase, nil)
		log.Errorf(err, "update bill category data error")
		return
	}
}

func Delete(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		log.Info("delete bill id is null")
		handler.SendResponse(c, errno.ErrBind, nil)
		return
	}
	bill, err := model.GetBillCategoryById(id)
	if err != nil {
		handler.SendResponse(c, errno.ErrDatabase, nil)
		log.Errorf(err, "查询bill category错误")
		return
	}
	if err := model.DeleteBillCategory(id); err != nil {
		handler.SendResponse(c, errno.ErrDatabase, nil)
		log.Errorf(err, "删除bill category错误")
		return
	}
	handler.SendResponse(c, nil, bill)
}

func Get(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		log.Error("id is empty", nil)
	}
	bill, err := model.GetBillCategoryById(id)
	if err != nil {

		handler.SendResponse(c, errno.ErrDatabase, nil)
		log.Errorf(err, "获取bill category 错误,id:%s", id)
		return
	}
	handler.SendResponse(c, nil, bill)
}

func List(c *gin.Context) {
	offset, err := strconv.Atoi(c.Query("offset"))
	if err != nil {
		handler.SendResponse(c, errors.New("offset参数有误"), nil)
		return
	}
	limit, err := strconv.Atoi(c.Query("limit"))
	if err != nil {
		limit = 10
	}

	bills, count, err := model.ListBillCategory(offset, limit)
	if err != nil {
		handler.SendResponse(c, errno.ErrDatabase, nil)
		log.Errorf(err, "list bill category error")
		return
	}
	response := resp.ListResponse{
		Rows:  bills,
		Count: count,
	}
	handler.SendResponse(c, nil, response)
}

func GetBillCategories() []*model.BillCategory {
	billCategories, _, _ := model.ListBillCategory(0, 100)
	return billCategories
}
